/**
 * 
 */
package com.ld.tamp.web.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ld.tamp.web.bean.AuthorizerInfo;

import weixin.popular.bean.component.ApiQueryAuthResult.Authorization_info;
import weixin.popular.bean.component.AuthorizerAccessToken;

/**
 * @author KeYang
 *
 */
@Component
public class AuthorizerInfoDao {

	private static final String AUTHORIZER_INFO = "Authorizer_Info";

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	public void save(Authorization_info authorizationInfo) {
		AuthorizerInfo authorizerInfo = new AuthorizerInfo(authorizationInfo);
		redisTemplate.opsForHash().put(AUTHORIZER_INFO, authorizationInfo.getAuthorizer_appid(), JSON.toJSONString(authorizerInfo));
	}

	public AuthorizerInfo read(String appid) {
		String authorizerInfoJson = (String) redisTemplate.opsForHash().get(AUTHORIZER_INFO, appid);
		AuthorizerInfo authorizerInfo = JSON.parseObject(authorizerInfoJson, AuthorizerInfo.class);
		return authorizerInfo;
	}

	public Map<String, AuthorizerInfo> readEntries() {

		Map<String, AuthorizerInfo> result = new HashMap<String, AuthorizerInfo>();
		Map<Object, Object> map = redisTemplate.opsForHash().entries(AUTHORIZER_INFO);
		Iterator<Entry<Object, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<Object, Object> entry = iterator.next();
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			AuthorizerInfo authorizerInfo = JSON.parseObject(value, AuthorizerInfo.class);
			result.put(key, authorizerInfo);
		}
		return result;
	}

	/**
	 * @param authorizer_appid
	 * @param authorizerAccessToken
	 */
	public void update(String authorizerAppid, AuthorizerAccessToken authorizerAccessToken) {
		AuthorizerInfo authorizerInfo = read(authorizerAppid);
		authorizerInfo.setAuthorizer_access_token(authorizerAccessToken.getAuthorizer_access_token());
		authorizerInfo.setAuthorizer_refresh_token(authorizerAccessToken.getAuthorizer_refresh_token());
		authorizerInfo.setExpires_time(authorizerAccessToken.getExpires_in()*1000+System.currentTimeMillis());
		redisTemplate.opsForHash().put(AUTHORIZER_INFO, authorizerAppid, JSON.toJSONString(authorizerInfo));
	}

}